#include <QDebug>
#include <time.h>
#include <QTime>
#include <QPluginLoader>
#include <QDebug>
#include <time.h>
#include <QTime>
#include <QWidget>
#include <QtXml>
#include <QDomDocument>
#include <QDomElement>
#include <QDomNode>
#include <QXmlStreamReader>
#include <QFile>
#include <QFileDialog>
#include <QTreeWidget>
#include <QTextEdit>
#include <QByteArray>

#include "unionteccontrollerhmiinstance.h"
#include "tecpluginremoteinterface.h"

UnionTecControllerHMIInstance::UnionTecControllerHMIInstance(){
    this->ui = new Ui::TecControllerHomePage;    //初始化ui 指向UI界面
    this->ui->setupUi(this);                     //初始化UI界面中控件
    this->pRemoteHMI = nullptr;

    this->SignalSlotConnect();

    this->pDocumentModel = new QFileSystemModel();
    this->pDocumentModel->setRootPath(QDir::currentPath());
    this->ui->DocumnetTree->setModel(pDocumentModel);
    this->ui->DocumnetTree->setRootIndex(pDocumentModel->index("../SCRIPT"));

    this->ui->stackedWidget->setCurrentIndex(0);
    this->SendStateMachine = SendStateMachine_Default;
}

UnionTecControllerHMIInstance::~UnionTecControllerHMIInstance(){

}

void  UnionTecControllerHMIInstance::SignalSlotConnect(){
    connect(ui->HomeNew, SIGNAL(clicked(bool)), this, SLOT(onbtnclicked_HomeNew()));
    connect(ui->HomeOpen, SIGNAL(clicked(bool)), this, SLOT(onbtnclicked_HomeOpen()));
    connect(ui->HomeSelected, SIGNAL(clicked(bool)), this, SLOT(onbtnclicked_HomeSelected()));
}



QWidget* UnionTecControllerHMIInstance::getUiHandle(){
    return this;
}

void UnionTecControllerHMIInstance::timer_PluginFastTimerLoop(){
    if(pRemoteHMI != nullptr){
        pRemoteHMI->FastTimerLoop();
    }
}

void UnionTecControllerHMIInstance::timer_PluginSlowTimerLoop(){
    if(pRemoteHMI != nullptr){
        pRemoteHMI->SlowTimerLoop();
    }
}

void UnionTecControllerHMIInstance::slots_onbtnclicked_Home(){
    this->ui->stackedWidget->setCurrentIndex(0);
}

void UnionTecControllerHMIInstance::slots_onbtnclicked_Setting(){
    this->ui->stackedWidget->setCurrentIndex(3);
}

void UnionTecControllerHMIInstance::slots_onbtnclicked_Edit(){

}

bool UnionTecControllerHMIInstance::slots_onbtnclicked_Pause(){
    this->stPluginInfo.Status = "Pause";
    this->SendStateMachine = SendStateMachine_System;
    return 1;
}

bool UnionTecControllerHMIInstance::slots_onbtnclicked_Run(){
    QString TecPluginRemoteDir = this->stPluginInfo.HmiName;
    if(this->pRemoteHMI == nullptr){
       QPluginLoader pluginLoader(QCoreApplication::applicationDirPath() + "/" + TecPluginRemoteDir);
        this->pRemoteHMI = qobject_cast<tecPluginRemoteHmiInterface*>(pluginLoader.instance());
        if(this->pRemoteHMI != nullptr){
            this->ui->stackedWidget->insertWidget(2,pRemoteHMI->RegisiterPluginUi());
        }
    }
    this->stPluginInfo.Status = "Run";
    this->SendStateMachine = SendStateMachine_System;
    return 1;
}

bool UnionTecControllerHMIInstance::slots_onbtnclicked_Stop(){
    this->stPluginInfo.Status = "Stop";
    this->SendStateMachine = SendStateMachine_System;
    return 1;
}

void UnionTecControllerHMIInstance::slots_onbtnclicked_fn1(){}

void UnionTecControllerHMIInstance::slots_onbtnclicked_fn2(){

}

void UnionTecControllerHMIInstance::slots_onbtnclicked_fn3(){

}

void UnionTecControllerHMIInstance::slots_onbtnclicked_fn4(){

}

void UnionTecControllerHMIInstance::slots_onbtnclicked_MainScriptStatus(){

}

void UnionTecControllerHMIInstance::slots_onbtnclicked_VisHmi(){
    if(pRemoteHMI != NULL){
        this->ui->stackedWidget->setCurrentIndex(2);
    }
}

void UnionTecControllerHMIInstance::message_fromBackendMessageCommand(QByteArray Data){
    if(pRemoteHMI != nullptr){
        pRemoteHMI->BackendDataRecv(Data);
    }
}

void UnionTecControllerHMIInstance::message_toBackendMessage(QByteArray& Data){
    switch (this->SendStateMachine) {
        case SendStateMachine_Default:
            break;
        case SendStateMachine_System:
            this->SystemMessageSendtoBackend(Data);
            this->SendStateMachine = SendStateMachine_Plugin;
            break;
        case SendStateMachine_Plugin:
            if(pRemoteHMI != nullptr){
                pRemoteHMI->BackendDataSend(Data);
            }
            else{
                this->SendStateMachine = SendStateMachine_Default;
            }
            break;
        default:
            break;
    }
}

void  UnionTecControllerHMIInstance::SystemMessageSendtoBackend(QByteArray& Data){
    QString SendString;
    QXmlStreamWriter stream(&SendString);

    stream.writeStartElement("UnionHim");
        stream.writeAttribute("Hmi","HmiSystem");
            stream.writeTextElement("Sender","HMISYSTEM");
            stream.writeTextElement("Status",this->stPluginInfo.Status);
            stream.writeTextElement("Type",this->stPluginInfo.Type);
            stream.writeTextElement("Name",this->stPluginInfo.Name);
    stream.writeEndElement();
    Data = SendString.toLocal8Bit();
}

void UnionTecControllerHMIInstance ::onbtnclicked_HomeNew(){

}

void UnionTecControllerHMIInstance ::onbtnclicked_HomeOpen(){
    QString FileDir = pDocumentModel->filePath(this->ui->DocumnetTree->selectionModel()->selectedIndexes().first());
    QFile ScriptFile(FileDir);
    if(ScriptFile.exists()){
        if(ScriptFile.open(QIODevice::ReadOnly)) {
        ui->ScriptTree->clear();
        ui->ScriptTree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
        ui->ScriptTree->expandAll();
            QDomDocument dom("ScriptXML");
            if (dom.setContent(&ScriptFile)){
                ui->ScriptTree->clear();
                ui->ScriptTree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
                QDomElement docElem = dom.documentElement();
                RecurrenceAnalysisScriptXML(docElem, NULL);
                ui->ScriptTree->expandAll();
            }
        }
        this->ui->stackedWidget->setCurrentIndex(1);
        ScriptFile.close();
    }
    else{
        this->ui->stackedWidget->setCurrentIndex(0);
    }
}

void UnionTecControllerHMIInstance ::onbtnclicked_HomeSelected(){
    QString FileDir = pDocumentModel->filePath(this->ui->DocumnetTree->selectionModel()->selectedIndexes().first());
    QFile ScriptFile(FileDir);
    if(ScriptFile.exists()){
        if(ScriptFile.open(QIODevice::ReadOnly)) {
            QDomDocument dom("ScriptXML");
            if (dom.setContent(&ScriptFile)){
                ui->ScriptTree->clear();
                ui->ScriptTree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
                QDomElement docElem = dom.documentElement();
                RecurrenceAnalysisScriptXML(docElem, NULL);
                ui->ScriptTree->expandAll();
            }
        }
        this->ui->stackedWidget->setCurrentIndex(1);
        ScriptFile.close();
    }
    else{
        this->ui->stackedWidget->setCurrentIndex(0);
    }
}

void UnionTecControllerHMIInstance ::RecurrenceAnalysisScriptXML(QDomElement &docElem, QTreeWidgetItem *pItem){
    bool SystemStatusChange = false;
    QDomNode node = docElem.firstChild();
    if(node.toElement().isNull()){
        if( pItem ){
               pItem->setText (1, docElem.text());
           }
    }
    if(!docElem.attributes().isEmpty()){
        QDomNamedNodeMap map = docElem.attributes();
        for(int i = 0 ; i < map.length() ; ++i){
            if(!(map.item(i).isNull())){
                QDomNode debug = map.item(i);
                QDomAttr attr = debug.toAttr();
                if(!attr.isNull()){
                    if( pItem ){
                        QTreeWidgetItem *item;
                        pItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt:: ItemIsSelectable);
                        item = new QTreeWidgetItem(pItem);
                        item->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt:: ItemIsSelectable);
                        item->setText(0, attr.name());
                        item->setText (1, attr.value());
                    }
                }
            }
        }
    }
    while(!node.isNull()){
        QDomElement element = node.toElement();
        if(!element.isNull()){
            QTreeWidgetItem *item;
            if( pItem ){
                pItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt:: ItemIsSelectable);
                item = new QTreeWidgetItem(pItem);
            }
            else{
                item = new QTreeWidgetItem(ui->ScriptTree);
            }
            item->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt:: ItemIsSelectable);
            item->setText(0, element.tagName());
            RecurrenceAnalysisScriptXML(element, item);
            if( pItem ){
                pItem->addChild(item);
            }
            else{
                ui->ScriptTree->addTopLevelItem(item);
            }

            if(element.tagName() == "PluginType"){
                 this->stPluginInfo.Type = element.text();
            }
            else if(element.tagName() == "PluginName"){
                 this->stPluginInfo.Name = element.text();
                SystemStatusChange = true;
            }
            else if(element.tagName() == "PluginHmiName"){
                 this->stPluginInfo.HmiName = element.text();
                SystemStatusChange = true;
            }
        }
            node = node.nextSibling();
    }
    if(SystemStatusChange == true){
        this->stPluginInfo.Status = "New";
        this->SendStateMachine = SendStateMachine_System;
    }
}




